﻿using AutoMapper;
using MediatR;
using SqlSugar;
using WarehouseManagement.Application.Command.AllocateCommand;
using WarehouseManagement.Domain.Entity;
using WarehouseManagement.Infrstructre.Interface;

namespace WarehouseManagement.Application.CommandHandler.AllocateCommandHandler
{
    /// <summary>
    /// 修改仓库调拨
    /// </summary>
    public class AllocateUpdCommandHandler : IRequestHandler<AllocateUpdCommand, int>
    {
        private readonly IAllocateRepository _allocateRep;
        private readonly IAllocationProductsRepository _allocationProductsRep;
        private readonly lnterfaceStorageProductRepository _storageProductRep;
        private readonly lnterfaceWarehouseSAppRepository _warehouseSAppRep;
        protected readonly IMapper _mapper;
        protected readonly ISqlSugarClient db;

        public AllocateUpdCommandHandler(IAllocateRepository allocateRep, IAllocationProductsRepository allocationProductsRep, lnterfaceStorageProductRepository storageProductRep, lnterfaceWarehouseSAppRepository warehouseSAppRep, IMapper mapper, ISqlSugarClient db)
        {
            this._allocateRep = allocateRep;
            this._allocationProductsRep = allocationProductsRep;
            this._storageProductRep = storageProductRep;
            this._warehouseSAppRep = warehouseSAppRep;
            this._mapper = mapper;
            this.db = db;
        }

        public async Task<int> Handle(AllocateUpdCommand request, CancellationToken cancellationToken)
        {
            // 开启事务
            db.Ado.BeginTran();
            try
            {
                //修改采购退货
                var se = await db.Queryable<Allocate>()
                                 .Where(c => c.AllocateId == request.updDto.AllocateId)
                .FirstAsync();

                var preProduction = _mapper.Map<Allocate>(request.updDto);
                int Item = await _allocateRep.UpdateAsync(preProduction);


                //删除调拨申请产品表中原有的数据
                var itemsToDelete = await db.Queryable<AllocationProducts>()
                                  .Where(c => c.ANumber == se.ANumber)
                                  .ToListAsync();
                foreach (var item in itemsToDelete)
                {
                    await _allocationProductsRep.DelRange(new List<AllocationProducts> { item });
                }


                foreach (var subpiece in request.updDto.upddto)
                {
                    AllocationProducts items = new AllocationProducts();
                    items.AllocationProductsId = subpiece.AllocationProductsId;
                    items.ANumber = preProduction.ANumber;
                    items.APAllocateNum = subpiece.APAllocateNum;
                    items.APInboundWarehouse = subpiece.APInboundWarehouse;
                    items.PNumber = subpiece.PNumber;
                    items.PName = subpiece.PName;
                    items.PSpec = subpiece.PSpec;
                    items.PUnit = subpiece.PUnit;
                    items.WName = subpiece.WName;
                    items.SPConfirmNum = subpiece.SPConfirmNum;
                    items.AddName = preProduction.AddName;
                    items.AddTime = preProduction.AddTime;
                    items.UpdName = preProduction.UpdName;
                    items.UpdTime = preProduction.UpdTime;
                    items.Office_Id = preProduction.Office_Id;
                    items.User_Id = preProduction.User_Id;
                    await _allocationProductsRep.AddAsync(items);
                }

                ////修改出库后的库存
                //var inwarehouse = (await _storageProductRep.GetAll()).Where(t => t.PNumber == request.updDto.upddto[0].PNumber).ToList();
                //inwarehouse.FirstOrDefault().SPConfirmNum -= (int)request.updDto.upddto[0].APAllocateNum;
                //await _storageProductRep.UpdateAsync(inwarehouse.First());

                //修改入库的库存
                //var outwarehouse = (await _warehouseSAppRep.GetAll()).Where(t => t.WName == request.addDto.adddto[0].APInboundWarehouse).ToList();
                //outwarehouse.FirstOrDefault().SPConfirmNum += (int)request.addDto.adddto[0].APAllocateNum;
                //await _storageProductRep.UpdateAsync(outwarehouse);

                // 提交事务
                db.Ado.CommitTran();
                return 1;
            }
            catch (Exception ex)
            {
                // 捕获异常并回滚事务
                db.Ado.RollbackTran();
                // 可以记录日志以便调试
                throw new Exception("事务失败，已回滚所有操作", ex);
            }
        }
    }
}
